import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Button, Select } from 'antd';

import { filterAssignArr } from '@/utils/tools';

import TagsBlock from '../tagsBlock';

import {
  DataSourceItem,
  SelectDetailProps,
} from '@/pages/features/userPermission/user/add/types/interface';

const SelectDetail: React.FC<SelectDetailProps> = (props) => {
  const {
    visible,
    title,
    dataSource,
    checkKeys,
    handleOkCallback,
    handleCancelCallback,
  } = props;
  const [_dataSource, setDataSource] = useState<DataSourceItem[]>([]);
  const [_checkKeys, setcheckKeys] = useState([]);
  const [_tagsDataSource, settagsDataSource] = useState<DataSourceItem[]>([]);

  useEffect(() => {
    initData();
  }, [visible]);

  const initData = () => {
    setDataSource(JSON.parse(JSON.stringify(dataSource)));
    setcheckKeys(JSON.parse(JSON.stringify(checkKeys)));
    settagsDataSource(filterAssignArr(checkKeys, dataSource, 'value'));
  };
  const removeCurrentTagHandle = (val: string) => {
    const newTags = _tagsDataSource.filter((item) => item.value !== val);
    const keys = newTags.map((item) => item.value);
    setcheckKeys(keys);
    settagsDataSource(newTags);
  };
  const handleChange = (vals: string[], items: any[]) => {
    console.log(vals, items);
    let tagsDataSource = items.map((item) => ({
      value: item.value,
      label: item.children,
    }));
    setcheckKeys(vals);
    settagsDataSource(tagsDataSource);
  };
  return (
    <>
      <Modal
        title={title}
        visible={visible}
        onOk={() => {
          handleOkCallback(_checkKeys, _tagsDataSource);
        }}
        onCancel={handleCancelCallback}
        width="60%"
      >
        <div>
          <div>
            <Select
              mode="multiple"
              allowClear
              style={{ width: '100%' }}
              placeholder="Please select"
              value={_checkKeys}
              onChange={handleChange}
            >
              {_dataSource.map((item) => (
                <Select.Option key={item.value} value={item.value}>
                  {item.label}
                </Select.Option>
              ))}
            </Select>
          </div>
          <div style={{ marginTop: '10px' }}>
            <TagsBlock
              dataSource={_tagsDataSource}
              removeCurrentTag={removeCurrentTagHandle}
            ></TagsBlock>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default SelectDetail;
